<!--
* description: 文件上传（单文件）
* author: wangml
* createdDate: 2020-01-28
-->
<template>
  <el-col
    :span="span"
    :style="{
      minHeight: '100px',
      marginTop: '10px'
    }"
  >
    <section>
      <lableName
        :validrule="validrule"
        :cur-label-name="curLabelName"
        :is-show-label="isShowLabel"
        :is-require="isRequire"
      />
      <div class="img-container">
        <el-upload
          ref="upload"
          slot="append"
          class="upload-demo"
          action
          :http-request="handleChange"
          :before-upload="beforeAvatarUpload"
          :show-file-list="false"
        >
          <el-button
            v-if="dataToObject.isUpload"
            size="small"
            type="primary"
          >点击上传</el-button>
          <i v-show="showLoading" class="el-icon-loading" />
        </el-upload>
        <transition name="fade-transform" mode="out-in">
          <div v-show="imgUrl" class="img-wrapper">
            <el-image
              v-if="imgUrl"
              ref="preImg"
              style="width: 100px; height: 100px"
              :src="imgUrl"
              :preview-src-list="srcList"
              :z-index="5000"
            />
            <i v-if="dataToObject.isUpload" class="el-icon-close ccl" @click="delCurImg" />
            <div class="upload-list">
              <i class="el-icon-check" />
            </div>
          </div>
        </transition>

      </div>
      <validateFormate
        ref="validComp"
        :cur-label-name="curLabelName.substring(0, curLabelName.indexOf('：'))"
        :validrule="validrule"
      />
    </section>
  </el-col>
</template>
<script>

export default {
  name: 'UploadFile',
  components: {
    lableName: () => import('@/components/lableName'), // 标题溢出样式组件
    validateFormate: () => import('@/components/validateFormate') // 校验提示样式组件
  },
  props: {
    validrule: { type: Object, default: () => {} },
    isRequire: { type: Boolean, default: false },
    isShowLabel: { type: Boolean, default: true },
    span: { type: Number, default: 6 },
    labelName: { type: String, default: '' },
    // 组件传值字段名称（与code对象绑定的字段名称，即视图中：formField对应的字段名称）
    // 如：视图中配置：code="formField.carBrandCode"，则codeField="carBrandCode"
    codeField: { type: String, default: '' },
    // 上次文件目录
    category: { type: String, default: 'commonUpload' },
    // mp功能url路径 属性:fileUrl
    dataToObject: { type: Object, default: () => ({ isUpload: true }) },
    code: { type: String, default: '' }
  },
  data() {
    return {
      showLoading: false,
      srcList: [],
      imgUrl: '',
      fileList: null,
      modeCode: '',
      allowedFileExtension: ['jpg', 'jpeg', 'png', 'JPG', 'JPEG'],
      curLabelName:
        this.labelName === ''
          ? this.$t('sys.button.selFile') /* 选择文件*/
          : this.labelName
    }
  },
  watch: {
    'modeCode': {
      handler(val) {
        if (val) {
          this.$refs['validComp'].iconV = '2'
        } else {
          this.$refs['validComp'].iconV = ''
        }
      }
    },
    'code': {
      handler(val) {
        console.log(val, 2)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.initImg()
      }, 500)
    })
  },
  methods: {
    initImg() {
      if (this.code !== '') {
        this.imgUrl = this.code
        this.srcList.push(this.code)
      }
    },
    delCurImg() {
      this.srcList = []
      this.imgUrl = ''
      this.modeCode = ''
      // 弹窗页面组件 formField 对应的 图片url地址置空
      this.$parent.$parent.$parent.formField[this.codeField] = ''
    },
    // 文件格式过滤
    beforeAvatarUpload(file) {
      const curFileExtension = file.name.split('.')[1]
      let flag = true
      if (!this.allowedFileExtension.includes(curFileExtension)) {
        flag = false
        this.$message(`只能上传${this.allowedFileExtension.join(', ')}格式文件，请重新选择!`)
      }
      if (file.size / 1024 / 1024 > 2) {
        flag = false
        this.$message('上传图片大小不能超过 2MB!')
      }
      return flag
    },
    // 处理上传事件
    handleChange(param) {
      // const that = this
      this.showLoading = true
      const url = this.dataToObject.fileUrl || '/mp/file/notice/upload.do'
      this.$requestUpload(url, param).then(response => {
        if (response.result === '1') {
          this.modeCode = ''
          let code = ''; const text = ''
          if (typeof response.path !== 'undefined') {
            if (
              response.path.length > 0 &&
                response.path[0].length > 0 &&
                response.path[0][0].indexOf('|') > -1
            ) {
              // 返回格式：[["xxxx.png|/upload/{category}/{yyyyMMdd}/{guid}/xxxx.jpg","xxx.xx KB"]]
              // 截取出/upload/{category}/{yyyyMMdd}/{guid}/xxxx.jpg返回
              this.modeCode = response.path[0][0].split('|')[1]
              code = this.modeCode
            }
          }
          this.imgUrl = window.URL.createObjectURL(param.file)
          this.showLoading = false
          this.srcList = [this.imgUrl]
          // this.$message({ message: "图片上传成功", type: "success" })
          this.$emit('changeCode', code, text, this.codeField, this.comType)
        } else {
          this.$message({ message: '文件上传失败', type: 'warning' })
        }
      })
        .catch(err => {
          this.modeCode = ''
          this.showLoading = false
          console.info(err)
        })
    }
  }
}
</script>

<style lang="scss">

  div.img-container {
    display: flex;
    justify-content: left;
    .upload-demo {
      /*overflow: hidden;*/
      i.el-icon-loading {
        margin-left: 3px;
      }
    }
    & .cssvalidateFormate {
      position: static;
      margin-left: 5px;
      width: 12px;
      height: 24px;
    }
    div.img-wrapper {
      overflow: hidden;
      position: relative;
      border-radius: 6px;
      .el-image {
        border: #CCCCCC 1px dashed;
        border-radius: 6px;
        margin-left: 8px;
        &:hover {
          border: #00a0e9 1px dashed;
          border-radius: 6px;
          margin-left: 8px;
        }
      }
      & i.el-icon-close.ccl {
        position: absolute;
        top:2px;
        right: 2px;
        cursor: pointer;
        color: #606266;
        font-size: 17px;
        &:hover {
          color: #000;
        }
      }
      div.upload-list {
        cursor: pointer;
        position: absolute;
        padding-top: 3px;
        right: -20px;
        top: 0;
        width: 40px;
        height: 20px;
        background: #13ce66;
        text-align: center;
        transform-origin: top center;
        transform: rotate(45deg);
        box-shadow: 0 1px 1px #ccc;
        transition: .2s;
        & i.el-icon-check {
          color: #fff;
          transform: rotate(-45deg);
        }
        &:hover {
          right: -25px;
          top: -25px;
          transform: rotate(45deg);
        }
      }
      &:hover div.upload-list {
        right: -25px;
        top: -25px;
        transform: rotate(45deg);
      }
    }
  }
  /* fade-transform */
  .fade-transform-leave-active,
  .fade-transform-enter-active {
    transition: all .5s;
  }

  .fade-transform-enter {
    opacity: 0;
    transform: translateX(-30px);
  }

  .fade-transform-leave-to {
    opacity: 0;
    transform: translateX(30px);
  }
  i.el-icon-circle-close {
    background: none;
  }

</style>

